<template>
  <view class="room-rule-manage-container">
    <view class="page-header">
      <text class="page-title">房间规则管理</text>
      <text class="page-subtitle">房间: {{ roomName }}</text>
    </view>

    <view class="rule-list-section">
      <view class="list-header">
        <text class="section-title">规则列表</text>
        <view class="header-actions">
          <button class="create-btn" @click="openAddRuleModal">添加规则</button>
          <text class="list-count">共 {{ ruleList.length }} 个规则</text>
        </view>
      </view>

      <view v-if="loading" class="loading-container">
        <view class="loading-spinner"></view>
        <text>加载中...</text>
      </view>
      
      <view v-else-if="ruleList.length === 0" class="empty-state">
        <text>该房间下暂无规则</text>
      </view>

      <view v-else class="rule-list">
        <view 
          class="rule-item" 
          v-for="rule in ruleList" 
          :key="rule.id"
        >
          <view class="rule-header">
            <text class="rule-id">规则ID: {{ rule.id }}</text>
            <view class="rule-actions">
              <button class="edit-btn" @click="editRule(rule)">编辑</button>
              <button class="delete-btn" @click="deleteRule(rule)">删除</button>
            </view>
          </view>
          
          <view class="rule-info">
            <view class="info-row">
              <text class="info-label">起始点:</text>
              <text class="info-value">{{ rule.startPoint || '未设置' }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">结束点:</text>
              <text class="info-value">{{ rule.endPoint || '未设置' }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">准备时间:</text>
              <text class="info-value">{{ formatTime(rule.prepareTime) }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">限制时间:</text>
              <text class="info-value">{{ formatTime(rule.limitTime) }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">回合数:</text>
              <text class="info-value">{{ rule.round || '未设置' }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">得分模式:</text>
              <text class="info-value">{{ getScoreModelText(rule.scoreModel) }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">对战模式:</text>
              <text class="info-value">{{ getBattleModelText(rule.battleModel) }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">创建时间:</text>
              <text class="info-value">{{ formatDate(rule.createTime) }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 添加/编辑规则模态框 -->
    <view class="modal-overlay" v-if="showRuleFormModal" @click="closeRuleFormModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">{{ isEditingRule ? '编辑规则' : '添加规则' }}</text>
          <button class="close-btn" @click="closeRuleFormModal">×</button>
        </view>
        
        <view class="modal-body">
          <view class="form-section">
            <view class="form-item">
              <text class="form-label">起始点</text>
              <input 
                class="form-input" 
                v-model="ruleForm.startPoint" 
                placeholder="请输入起始点"
              />
            </view>
            
            <view class="form-item">
              <text class="form-label">结束点</text>
              <input 
                class="form-input" 
                v-model="ruleForm.endPoint" 
                placeholder="请输入结束点"
              />
            </view>
            
            <view class="form-item">
              <text class="form-label">准备时间（秒）</text>
              <input 
                class="form-input" 
                v-model="ruleForm.prepareTimeSeconds" 
                type="number"
                placeholder="请输入准备时间（秒）"
              />
            </view>
            
            <view class="form-item">
              <text class="form-label">限制时间（秒）</text>
              <input 
                class="form-input" 
                v-model="ruleForm.limitTimeSeconds" 
                type="number"
                placeholder="请输入限制时间（秒）"
              />
            </view>
            
            <view class="form-item">
              <text class="form-label">回合数</text>
              <input 
                class="form-input" 
                v-model="ruleForm.round" 
                type="number"
                placeholder="请输入回合数"
              />
            </view>
            
            <view class="form-item">
              <text class="form-label">得分模式</text>
              <view class="form-picker" @click="openScoreModelPicker">
                <view class="picker-text">{{ scoreModelOptions[scoreModelIndex] || '请选择得分模式' }}</view>
                <view class="picker-arrow">▼</view>
              </view>
            </view>
            
            <view class="form-item">
              <text class="form-label">对战模式</text>
              <view class="form-picker" @click="openBattleModelPicker">
                <view class="picker-text">{{ battleModelOptions[battleModelIndex] || '请选择对战模式' }}</view>
                <view class="picker-arrow">▼</view>
              </view>
            </view>
          </view>
        </view>
        
        <view class="modal-footer">
          <button class="cancel-btn" @click="closeRuleFormModal">取消</button>
          <button class="submit-btn" @click="saveRule" :disabled="submitting">
            {{ submitting ? '保存中...' : '保存' }}
          </button>
        </view>
      </view>
    </view>
    
    <!-- 得分模式选择模态框 -->
    <view class="modal-overlay" v-if="showScoreModelPicker" @click="closeScoreModelPicker">
      <view class="picker-modal-content" @click.stop>
        <view class="picker-modal-header">
          <text class="picker-modal-title">选择得分模式</text>
          <button class="close-btn" @click="closeScoreModelPicker">×</button>
        </view>
        <view class="picker-modal-body">
          <view 
            class="picker-option" 
            v-for="(option, index) in scoreModelOptions" 
            :key="index"
            @click="selectScoreModel(index)"
            :class="{ 'selected': scoreModelIndex === index }"
          >
            <text class="option-text">{{ option }}</text>
            <view class="option-check" v-if="scoreModelIndex === index">✓</view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 对战模式选择模态框 -->
    <view class="modal-overlay" v-if="showBattleModelPicker" @click="closeBattleModelPicker">
      <view class="picker-modal-content" @click.stop>
        <view class="picker-modal-header">
          <text class="picker-modal-title">选择对战模式</text>
          <button class="close-btn" @click="closeBattleModelPicker">×</button>
        </view>
        <view class="picker-modal-body">
          <view 
            class="picker-option" 
            v-for="(option, index) in battleModelOptions" 
            :key="index"
            @click="selectBattleModel(index)"
            :class="{ 'selected': battleModelIndex === index }"
          >
            <text class="option-text">{{ option }}</text>
            <view class="option-check" v-if="battleModelIndex === index">✓</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { MatchRoomRuleAPI } from '@/api/battle.js'

const loading = ref(false)
const ruleList = ref([])
const roomId = ref('')
const roomName = ref('')

// 规则表单相关数据
const showRuleFormModal = ref(false)
const submitting = ref(false)
const isEditingRule = ref(false)
const currentRule = ref(null)

// 选择器相关数据
const showScoreModelPicker = ref(false)
const showBattleModelPicker = ref(false)

// 规则表单数据
const ruleForm = ref({
  startPoint: '',
  endPoint: '',
  prepareTimeSeconds: '',
  limitTimeSeconds: '',
  round: '',
  scoreModel: 0,
  battleModel: 0
})

const scoreModelIndex = ref(0)
const battleModelIndex = ref(0)

// 得分模式映射
const scoreModelMap = {
  0: '不记分',
  1: '时间短',
  2: '时间长',
  3: '距离短',
  4: '距离长',
  5: '得分少',
  6: '得分多',
  7: '步数短',
  8: '步数长'
}

// 对战模式映射
const battleModelMap = {
  0: '接力',
  1: '单回合',
  2: '多回合'
}

const scoreModelOptions = [
  '不记分',
  '时间短',
  '时间长',
  '距离短',
  '距离长',
  '得分少',
  '得分多',
  '步数短',
  '步数长'
]

const battleModelOptions = [
  '接力',
  '单回合',
  '多回合'
]

const getScoreModelText = (scoreModel) => scoreModelMap[scoreModel] || '未知'
const getBattleModelText = (battleModel) => battleModelMap[battleModel] || '未知'

const formatDate = (timestamp) => {
  if (!timestamp) return '未设置'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN')
}

const formatTime = (milliseconds) => {
  if (!milliseconds) return '未设置'
  const seconds = Math.floor(milliseconds / 1000)
  return `${seconds}秒`
}

const fetchRuleList = async () => {
  if (!roomId.value) return;
  loading.value = true
  try {
    const result = await MatchRoomRuleAPI.page({ 
      matchRoomId: roomId.value,
      pageNum: 0,
      pageSize: 100
    })
    console.log('规则查询API返回结果:', result)
    if (result.code === 0) {
      ruleList.value = result.data?.list || result.data || []
    } else {
      ruleList.value = []
      throw new Error(result.msg || '获取规则失败')
    }
  } catch (error) {
    console.error('获取规则失败:', error)
    uni.showToast({
      title: error.message || '获取规则失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

onLoad((options) => {
  if (options.roomId) {
    roomId.value = options.roomId
    roomName.value = decodeURIComponent(options.roomName || '')
    fetchRuleList()
  }
})

// 打开添加规则模态框
const openAddRuleModal = () => {
  isEditingRule.value = false
  currentRule.value = null
  resetRuleForm()
  showRuleFormModal.value = true
}

// 打开编辑规则模态框
const editRule = (rule) => {
  isEditingRule.value = true
  currentRule.value = rule
  fillRuleForm(rule)
  showRuleFormModal.value = true
}

// 关闭规则表单模态框
const closeRuleFormModal = () => {
  showRuleFormModal.value = false
  isEditingRule.value = false
  currentRule.value = null
  resetRuleForm()
}

// 重置规则表单
const resetRuleForm = () => {
  ruleForm.value = {
    startPoint: '',
    endPoint: '',
    prepareTimeSeconds: '',
    limitTimeSeconds: '',
    round: '',
    scoreModel: 0,
    battleModel: 0
  }
  scoreModelIndex.value = 0
  battleModelIndex.value = 0
}

// 填充规则表单
const fillRuleForm = (rule) => {
  ruleForm.value = {
    startPoint: rule.startPoint || '',
    endPoint: rule.endPoint || '',
    prepareTimeSeconds: rule.prepareTime ? Math.floor(rule.prepareTime / 1000) : '',
    limitTimeSeconds: rule.limitTime ? Math.floor(rule.limitTime / 1000) : '',
    round: rule.round || '',
    scoreModel: rule.scoreModel || 0,
    battleModel: rule.battleModel || 0
  }
  scoreModelIndex.value = rule.scoreModel || 0
  battleModelIndex.value = rule.battleModel || 0
}

// 打开得分模式选择模态框
const openScoreModelPicker = () => {
  showScoreModelPicker.value = true
}

// 打开对战模式选择模态框
const openBattleModelPicker = () => {
  showBattleModelPicker.value = true
}

// 关闭得分模式选择模态框
const closeScoreModelPicker = () => {
  showScoreModelPicker.value = false
}

// 关闭对战模式选择模态框
const closeBattleModelPicker = () => {
  showBattleModelPicker.value = false
}

// 保存规则
const saveRule = async () => {
  if (!ruleForm.value.startPoint.trim()) {
    uni.showToast({
      title: '请输入起始点',
      icon: 'none'
    })
    return
  }
  
  if (!ruleForm.value.endPoint.trim()) {
    uni.showToast({
      title: '请输入结束点',
      icon: 'none'
    })
    return
  }
  
  submitting.value = true
  try {
    const data = {
      matchRoomId: roomId.value,
      startPoint: ruleForm.value.startPoint,
      endPoint: ruleForm.value.endPoint,
      prepareTime: ruleForm.value.prepareTimeSeconds ? parseInt(ruleForm.value.prepareTimeSeconds) * 1000 : 0,
      limitTime: ruleForm.value.limitTimeSeconds ? parseInt(ruleForm.value.limitTimeSeconds) * 1000 : 0,
      round: ruleForm.value.round ? parseInt(ruleForm.value.round) : 1,
      scoreModel: ruleForm.value.scoreModel,
      battleModel: ruleForm.value.battleModel
    }
    
    let result
    if (isEditingRule.value) {
      result = await MatchRoomRuleAPI.edit({
        ...data,
        matchRoomRuleId: currentRule.value.id
      })
    } else {
      result = await MatchRoomRuleAPI.create(data)
    }
    
    if (result.code === 0) {
      uni.showToast({
        title: isEditingRule.value ? '更新成功' : '创建成功',
        icon: 'success'
      })
      closeRuleFormModal()
      fetchRuleList()
    } else {
      throw new Error(result.msg || (isEditingRule.value ? '更新失败' : '创建失败'))
    }
  } catch (error) {
    console.error('保存规则失败:', error)
    uni.showToast({
      title: error.message || '保存失败',
      icon: 'none'
    })
  } finally {
    submitting.value = false
  }
}

// 删除规则
const deleteRule = (rule) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除规则 "${rule.startPoint} -> ${rule.endPoint}" 吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await MatchRoomRuleAPI.remove({
            matchRoomRuleId: rule.id
          })
          
          if (result.code === 0) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })
            fetchRuleList()
          } else {
            throw new Error(result.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除规则失败:', error)
          uni.showToast({
            title: error.message || '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 选择得分模式
const selectScoreModel = (index) => {
  scoreModelIndex.value = index
  ruleForm.value.scoreModel = index
  closeScoreModelPicker()
}

// 选择对战模式
const selectBattleModel = (index) => {
  battleModelIndex.value = index
  ruleForm.value.battleModel = index
  closeBattleModelPicker()
}
</script>

<style lang="scss" scoped>
.room-rule-manage-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx;
}

.page-header {
  text-align: center;
  margin-bottom: 60rpx;
  
  .page-title {
    display: block;
    font-size: 48rpx;
    font-weight: bold;
    color: #fff;
    margin-bottom: 20rpx;
    text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
  }
  
  .page-subtitle {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.8);
  }
}

.rule-list-section {
  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    
    .section-title {
      color: #fff;
      font-size: 32rpx;
      font-weight: bold;
    }
    
    .header-actions {
      display: flex;
      align-items: center;
      gap: 15rpx;
      
      .create-btn {
        height: 60rpx;
        padding: 0 25rpx;
        border: none;
        border-radius: 12rpx;
        color: #fff;
        font-size: 24rpx;
        font-weight: bold;
        background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
      }
      
      .list-count {
        color: rgba(255, 255, 255, 0.8);
        font-size: 24rpx;
      }
    }
  }

  .loading-container, .empty-state {
    text-align: center;
    color: #fff;
    padding: 50rpx;
  }
  
  .rule-list .rule-item {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 20rpx;
    padding: 40rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);
      
    .rule-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30rpx;
      
      .rule-id {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
      
      .rule-actions {
        display: flex;
        gap: 15rpx;
        
        .edit-btn, .delete-btn {
          padding: 8rpx 20rpx;
          border: none;
          border-radius: 12rpx;
          color: #fff;
          font-size: 24rpx;
          font-weight: bold;
        }
        
        .edit-btn {
          background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
        }
        
        .delete-btn {
          background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
        }
      }
    }
      
    .rule-info {
      .info-row {
        display: flex;
        margin-bottom: 15rpx;
        font-size: 26rpx;
        
        .info-label { 
          width: 160rpx; 
          color: #666; 
        }
        .info-value { 
          flex: 1; 
          color: #333; 
        }
      }
    }
  }
}

// 全局样式，确保picker弹出框在最顶层
:deep(.uni-picker-container) {
  z-index: 99999 !important;
}

:deep(.uni-picker-view) {
  z-index: 99999 !important;
}

:deep(.uni-picker-mask) {
  z-index: 99998 !important;
}

// 选择器模态框样式
.picker-modal-content {
  width: 80%;
  max-height: 70%;
  background: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  position: relative;
  z-index: 10001;
  
  .picker-modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 2rpx solid #eee;
    background: #f8f9fa;
    
    .picker-modal-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .close-btn {
      width: 60rpx;
      height: 60rpx;
      border: none;
      background: none;
      font-size: 40rpx;
      color: #999;
    }
  }
  
  .picker-modal-body {
    max-height: 50vh;
    overflow-y: auto;
    
    .picker-option {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      border-bottom: 1rpx solid #eee;
      transition: background-color 0.3s ease;
      
      &:hover {
        background: #f8f9fa;
      }
      
      &.selected {
        background: #e3f2fd;
        border-left: 4rpx solid #007bff;
      }
      
      .option-text {
        font-size: 28rpx;
        color: #333;
      }
      
      .option-check {
        font-size: 32rpx;
        color: #007bff;
        font-weight: bold;
      }
    }
  }
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid #f3f3f3;
  border-top: 4rpx solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

// 降低模态框的z-index，避免遮挡picker
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  
  .modal-content {
    width: 90%;
    max-height: 80%;
    background: #fff;
    border-radius: 20rpx;
    overflow: hidden;
    position: relative;
    z-index: 10000;
    
    .modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      border-bottom: 2rpx solid #eee;
      
      .modal-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
      
      .close-btn {
        width: 60rpx;
        height: 60rpx;
        border: none;
        background: none;
        font-size: 40rpx;
        color: #999;
      }
    }
    
    .modal-body {
      padding: 30rpx;
      max-height: 60vh;
      overflow-y: auto;
      
      .form-section {
        .form-item {
          margin-bottom: 25rpx;
          position: relative;
          z-index: 1;
          
          .form-label {
            display: block;
            font-size: 26rpx;
            color: #333;
            font-weight: bold;
            margin-bottom: 10rpx;
          }
          
          .form-input {
            width: 100%;
            height: 70rpx;
            padding: 0 15rpx;
            border: 2rpx solid #ddd;
            border-radius: 8rpx;
            font-size: 26rpx;
            background: #fff;
            box-sizing: border-box;
            
            &:focus {
              border-color: #667eea;
            }
          }
          
          .form-picker {
            width: 100%;
            height: 70rpx;
            border: 2rpx solid #ddd;
            border-radius: 8rpx;
            background: #fff;
            position: relative;
            z-index: 2;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 15rpx;
            cursor: pointer;
            box-sizing: border-box;
            
            .picker-text {
              font-size: 26rpx;
              color: #333;
            }
            
            .picker-arrow {
              font-size: 24rpx;
              color: #999;
            }
          }
        }
      }
    }
    
    .modal-footer {
      display: flex;
      gap: 20rpx;
      padding: 30rpx;
      border-top: 2rpx solid #eee;
      
      .cancel-btn, .submit-btn {
        flex: 1;
        height: 80rpx;
        border: none;
        border-radius: 12rpx;
        font-size: 28rpx;
        font-weight: bold;
        
        &.cancel-btn {
          background: #f8f9fa;
          color: #666;
          border: 2rpx solid #eee;
        }
        
        &.submit-btn {
          background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
          color: #fff;
          
          &:disabled {
            opacity: 0.6;
          }
        }
      }
    }
  }
}
</style> 